package com.yh.hljapp.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yh.hljapp.AppConfig;
import com.yh.hljapp.AppContext;
import com.yh.hljapp.R;
import com.yh.hljapp.api.ErrorHandler;
import com.yh.hljapp.api.RetrofitSingleton;
import com.yh.hljapp.base.BaseFragment;
import com.yh.hljapp.common.FullyLinearLayoutManager;
import com.yh.hljapp.common.MyScrollview;
import com.yh.hljapp.common.PLog;
import com.yh.hljapp.common.StringUtils;
import com.yh.hljapp.common.TDevice;
import com.yh.hljapp.common.UIHelper;
import com.yh.hljapp.gddb.gbmanager.AddSale_Manager;
import com.yh.hljapp.gddb.gdbean.AddBack_HeadBean;
import com.yh.hljapp.gddb.gdbean.AddSaleInt_bodyBean;
import com.yh.hljapp.gddb.gdbean.AddSaleInt_body_InOutList_Bean;
import com.yh.hljapp.gddb.gdbean.Add_Sync_Bean;
import com.yh.hljapp.gddb.gdbean.Add_bodyBack_Bean;
import com.yh.hljapp.modules.adatper.Add_Saleback_Adapter;
import com.yh.hljapp.modules.bean.AddBack_HB_Bean;
import com.yh.hljapp.modules.bean.CM;
import com.yh.hljapp.modules.bean.CustPhone;
import com.yh.hljapp.modules.bean.Result;
import com.yh.hljapp.modules.bean.SimpleBackPage;
import com.yh.hljapp.modules.bean.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.yh.hljapp.AppConfig.SCN_CUST_ACTION_SCODE;

/**
 * =========================
 * 版权所有，违法必究
 * 作者：zhanghang
 * <p>
 * 工程：hlj
 * <p>
 * 文件名：ADDSaleIntFragment
 * <p>
 * 创建时间：2017.07.31.11:40
 */

public class ADDBackMatFragment extends BaseFragment implements Add_Saleback_Adapter.OnSaleAddAdapterListern {


    @InjectView(R.id.tv_gh_unit)
    TextView tvGhUnit;
    @InjectView(R.id.tv_zong)
    TextView tv_zong;
    @InjectView(R.id.tv_all)
    TextView tv_all;
    @InjectView(R.id.ll_gh_unit)
    LinearLayout llGhUnit;
    @InjectView(R.id.tv_zdr)
    TextView tvZdr;
    @InjectView(R.id.ll_zdr)
    LinearLayout llZdr;
    @InjectView(R.id.tv_fh)
    TextView tvFh;
    @InjectView(R.id.ll_fh)
    LinearLayout llFh;
    @InjectView(R.id.tv_ywy)
    TextView tvYwy;
    @InjectView(R.id.ll_ywy)
    LinearLayout llYwy;
    @InjectView(R.id.tv_bg)
    TextView tvBg;
    @InjectView(R.id.ll_bg)
    LinearLayout llBg;
    @InjectView(R.id.tv_sh_warehouse)
    TextView tvShWarehouse;
    @InjectView(R.id.ll_sh_warehouse)
    LinearLayout llShWarehouse;
    @InjectView(R.id.recyclerview)
    RecyclerView mRecycleview;
    @InjectView(R.id.scrollView)
    MyScrollview scrollView;

    private String currBillNumb;
    private Add_Saleback_Adapter mAdapter;
    ArrayList<Add_bodyBack_Bean> checkedCKS;
    private AddBack_HeadBean AddBack_HeadBean;
    //    private List<String> mFbillNumberList = new ArrayList<>();
    private int position;
    private boolean isSave;
    private String mType;
    private User mUser;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE)) {
                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
                JSONObject jo = null;
                try {
                    jo = new JSONObject(message);
                    final String fBase = jo.optString("FBase");
                    final String fWeight = jo.optString("FWeight");
                    String fBillNumber = jo.optString("FBillNumber");

                    currBillNumb = fBillNumber;
//                    mFbillNumberList.add(fBillNumber);

                    User currentUser = AppContext.getInstance().getCurrentUser();
                    if (currentUser == null) {
                        Snackbar.make(mActivity.getWindow().getDecorView(), "当前用户为空，请重新登陆", Snackbar.LENGTH_SHORT).show();
                    } else {
                        handleOtherText(fBase, fWeight);
                    }
                } catch (JSONException e) {
                    Snackbar.make(mActivity.getWindow().getDecorView(), "请扫描正确二维码!", Snackbar.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        }
    };

    private void handleOtherText(String text, String fWeight) {
        //先去判断扫描的单号是否存在
        boolean matExist = AddSale_Manager.getInstance(mActivity).isMatExist(text);
        if (matExist) {//存在
            onlyMatInsert(text, fWeight);
        } else {//不存在
            Snackbar.make(mActivity.getWindow().getDecorView(), "出库单不匹配，请重新扫描或同步数据！", Snackbar.LENGTH_SHORT).show();
        }
    }

    public int getHeight(View view) {// 获得某组件的高度
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        return view.getMeasuredHeight();
    }

    //扫描条码只对应一个物料时的添加流程
    private void onlyMatInsert(String barcode, String fWeight) {

        //先判断已添加的中是否存在
        List<Add_bodyBack_Bean> listMatBean = mAdapter.getBackList();
        for (int i = 0; i < listMatBean.size(); i++) {
            Add_bodyBack_Bean addSyncBean = listMatBean.get(i);
            String id = addSyncBean.getFBillNum();
            //判断是否添加一样
            if (currBillNumb.equals(id)) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "请确认该产品是否已经添加！", Snackbar.LENGTH_SHORT).show();
//                double count = Double.parseDouble(addSyncBean.getCount()) + (Integer.parseInt(fWeight));
//                addSyncBean.setCount(count + "");
//
//                mAdapter.notifyItemChanged(i);
//
//                final View childAt = mRecycleview.getChildAt(i);
//                final int finalI = i;
//                scrollView.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        int i1 = (getHeight(scrollView) - getHeight(mRecycleview)) + getHeight(childAt) * finalI;
//                        scrollView.smoothScrollTo(0, i1);
//                    }
//                });
                return;
            }
        }
        //设置数据
        Add_Sync_Bean matById = AddSale_Manager.getInstance(mActivity).getMatById(barcode);
        Add_bodyBack_Bean addSyncBean = new Add_bodyBack_Bean();

        addSyncBean.setUnit_id(matById.getUnit_id());
        addSyncBean.setId(matById.getId());
        addSyncBean.setCount(fWeight);
        addSyncBean.setModel(matById.getModel());
        addSyncBean.setName(matById.getName());
        addSyncBean.setNumber(matById.getNumber());
        addSyncBean.setUnitgroup_name(matById.getUnitgroup_name());
        addSyncBean.setUnit_name(matById.getUnit_name());
        addSyncBean.setDefunitId(matById.getDefunitId());
        addSyncBean.setBaseName(matById.getBaseName());
        addSyncBean.setBaseunit(matById.getBaseunit());
        addSyncBean.setUnitgroup_id(matById.getUnitgroup_id());
        addSyncBean.setFDCStockName(AddBack_HeadBean.getFDCStockIDName());
        addSyncBean.setFDCStockID(AddBack_HeadBean.getFDCStockID());
        addSyncBean.setFBillNum(currBillNumb);

        checkedCKS.add(addSyncBean);

        mAdapter = new Add_Saleback_Adapter(mActivity, checkedCKS, this);
        mRecycleview.setAdapter(mAdapter);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(mActivity, R.layout.fragment_sale_out, null);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }


    @Override
    public void initView(View view) {
        super.initView(view);
        TDevice.hideSoftKeyboard(mActivity);
        setHasOptionsMenu(true);
        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
        mActivity.registerReceiver(mSamDataReceiver, intentFilter);
        isSave = false;
        tv_all.setVisibility(View.GONE);
        tv_zong.setVisibility(View.GONE);
        llGhUnit.setOnClickListener(this);
        llZdr.setOnClickListener(this);
        llBg.setOnClickListener(this);
        llYwy.setOnClickListener(this);
        llShWarehouse.setOnClickListener(this);
        llFh.setOnClickListener(this);
        checkedCKS = new ArrayList<>();

        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(getContext());
        mRecycleview.setNestedScrollingEnabled(false);
        //设置布局管理器
        mRecycleview.setLayoutManager(linearLayoutManager);

        mAdapter = new Add_Saleback_Adapter(mActivity, checkedCKS, this);
    }

    @Override
    public void initData() {
        super.initData();
        mUser = AppContext.getInstance().getCurrentUser();
        AddBack_HeadBean = new AddBack_HeadBean();

        //text
        String ADDBacktvJhUnit = AppContext.getInstance().getProperty("ADDBacktvJhUnit");
        String ADDBacktvBg = AppContext.getInstance().getProperty("ADDBacktvBg");
        String ADDBacktvFh = AppContext.getInstance().getProperty("ADDBacktvFh");
        String ADDBacktvYwy = AppContext.getInstance().getProperty("ADDBacktvYwy");
        String ADDBacktvShWarehouse = AppContext.getInstance().getProperty("ADDBacktvShWarehouse");

        //id
        String ADDBacktvJhUnit_id = AppContext.getInstance().getProperty("ADDBacktvJhUnit_id");
        String ADDBacktvBg_id = AppContext.getInstance().getProperty("ADDBacktvBg_id");
        String ADDBacktvFh_id = AppContext.getInstance().getProperty("ADDBacktvFh_id");
        String ADDBacktvYwy_id = AppContext.getInstance().getProperty("ADDBacktvYwy_id");
        String ADDBacktvShWarehouse_id = AppContext.getInstance().getProperty("ADDBacktvShWarehouse_id");

        if (!StringUtils.isEmpty(ADDBacktvJhUnit) && !StringUtils.isEmpty(ADDBacktvBg) && !StringUtils.isEmpty(ADDBacktvFh)
                && !StringUtils.isEmpty(ADDBacktvYwy) && !StringUtils.isEmpty(ADDBacktvShWarehouse)) {

            tvGhUnit.setText(ADDBacktvJhUnit);
            tvBg.setText(ADDBacktvBg);
            tvFh.setText(ADDBacktvFh);
            tvYwy.setText(ADDBacktvYwy);
            tvShWarehouse.setText(ADDBacktvShWarehouse);

            AddBack_HeadBean.setFSupplyID(ADDBacktvJhUnit_id);
            AddBack_HeadBean.setFSupplyIDName(ADDBacktvJhUnit);

            AddBack_HeadBean.setFBUser(ADDBacktvBg_id);
            AddBack_HeadBean.setFBUserName(ADDBacktvBg);

            AddBack_HeadBean.setFYUser(ADDBacktvFh_id);
            AddBack_HeadBean.setFYUserName(ADDBacktvFh);

            AddBack_HeadBean.setFPUser(ADDBacktvYwy_id);
            AddBack_HeadBean.setFPUserName(ADDBacktvYwy);

            AddBack_HeadBean.setFDCStockID(ADDBacktvShWarehouse_id);
            AddBack_HeadBean.setFDCStockIDName(ADDBacktvShWarehouse);
        }

        Bundle bundle = getArguments();
        mType = bundle.getString("TYPE");
        if ("show".equals(mType)) {
            String headid = bundle.getString("ID");
            long Id = Long.parseLong(headid);
            AddBack_HeadBean = AddSale_Manager.getInstance(mActivity).getHeadByIdback(Id + "");
            if (AddBack_HeadBean != null) {
                tvGhUnit.setText(AddBack_HeadBean.getFSupplyIDName());
                tvZdr.setText(AddBack_HeadBean.getFUserName());
                tvFh.setText(AddBack_HeadBean.getFYUserName());
                tvYwy.setText(AddBack_HeadBean.getFPUserName());
                tvBg.setText(AddBack_HeadBean.getFBUserName());
                tvShWarehouse.setText(AddBack_HeadBean.getFDCStockIDName());
            }
            List<Add_bodyBack_Bean> backMatsByHeadId = AddSale_Manager.getInstance(mActivity).getBackMatsByHeadIdback(Id);
            checkedCKS.addAll(backMatsByHeadId);

            mAdapter = new Add_Saleback_Adapter(mActivity, checkedCKS, this);
            mRecycleview.setAdapter(mAdapter);
        } else {
            mAdapter = new Add_Saleback_Adapter(mActivity, checkedCKS, this);

        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.ll_gh_unit:
                bundle.putString("type", "ghdw");
                UIHelper.showSimpleBackForResult(this, mActivity, 1, SimpleBackPage.CUST_PHEON, bundle, "购货单位");
                break;
            case R.id.ll_zdr:
                bundle.putString("type", "zdr");
                UIHelper.showSimpleBackForResult(this, mActivity, 2, SimpleBackPage.CUST_PHEON, bundle, "制单人");
                break;
            case R.id.ll_bg:
                bundle.putString("type", "bg");
                UIHelper.showSimpleBackForResult(this, mActivity, 3, SimpleBackPage.CUST_PHEON, bundle, "保管");
                break;
            case R.id.ll_fh:
                bundle.putString("type", "fh");
                UIHelper.showSimpleBackForResult(this, mActivity, 4, SimpleBackPage.CUST_PHEON, bundle, "发货");
                break;
            case R.id.ll_ywy:
                bundle.putString("type", "ywy");
                UIHelper.showSimpleBackForResult(this, mActivity, 5, SimpleBackPage.CUST_PHEON, bundle, "业务员");
                break;
            case R.id.ll_sh_warehouse:
                bundle.putString("type", "fhck");
                UIHelper.showSimpleBackForResult(this, mActivity, 6, SimpleBackPage.CUST_PHEON, bundle, "发货仓库");
                break;

        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            final CustPhone item = (CustPhone) data.getSerializableExtra("item");
            if (item != null) {
                String name = item.getName();
                String id = item.getId();
                switch (requestCode) {
                    case 1:
                        tvGhUnit.setText(name);
                        AddBack_HeadBean.setFSupplyID(id);
                        AddBack_HeadBean.setFSupplyIDName(name);
                        AppContext.getInstance().setProperty("ADDBacktvJhUnit", name);
                        AppContext.getInstance().setProperty("ADDBacktvJhUnit_id", id);
                        break;
                    case 2:
                        tvZdr.setText(name);
                        break;
                    case 3:
                        tvBg.setText(name);
                        AddBack_HeadBean.setFBUser(id);
                        AddBack_HeadBean.setFBUserName(name);
                        AppContext.getInstance().setProperty("ADDBacktvBg", name);
                        AppContext.getInstance().setProperty("ADDBacktvBg_id", id);
                        break;
                    case 4:
                        tvFh.setText(name);
                        AddBack_HeadBean.setFYUser(id);
                        AddBack_HeadBean.setFYUserName(name);
                        AppContext.getInstance().setProperty("ADDBacktvFh", name);
                        AppContext.getInstance().setProperty("ADDBacktvFh_id", id);
                        break;
                    case 5:
                        tvYwy.setText(name);
                        AddBack_HeadBean.setFPUser(id);
                        AddBack_HeadBean.setFPUserName(name);
                        AppContext.getInstance().setProperty("ADDBacktvYwy", name);
                        AppContext.getInstance().setProperty("ADDBacktvYwy_id", id);
                        break;
                    case 6:
                        tvShWarehouse.setText(name);
                        AddBack_HeadBean.setFDCStockID(id);
                        AddBack_HeadBean.setFDCStockIDName(name);
                        AppContext.getInstance().setProperty("ADDBacktvShWarehouse", name);
                        AppContext.getInstance().setProperty("ADDBacktvShWarehouse_id", id);
                        break;
                    case 7://adapter中点击发货仓库 自选的仓库
                        ArrayList<Add_bodyBack_Bean> backList = mAdapter.getBackList();
                        Add_bodyBack_Bean addSyncBean = backList.get(position);
                        addSyncBean.setTDCStockID(item.getId());
                        addSyncBean.setTDCStockName(item.getName());
                        backList.set(position, addSyncBean);
                        mAdapter.setBackList(backList);
                        mAdapter.notifyItemChanged(position);
                        break;
                }
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_add_mat, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_btn:
                subMat();
                break;
            case R.id.btn_save:
                saveMat();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //提交
    private void subMat() {
        List<String> environmentList = new ArrayList<String>();
        ArrayList<Add_bodyBack_Bean> addSyncBeen_List = mAdapter.getBackList();
        if (addSyncBeen_List == null || addSyncBeen_List.size() == 0) {
            Snackbar.make(mActivity.getWindow().getDecorView(), "请扫描物料，再提交", Snackbar.LENGTH_SHORT).show();
            return;
        }
        for (int i = 0; i < addSyncBeen_List.size(); i++) {
            environmentList.add(addSyncBeen_List.get(i).getFBillNum());
        }

        //表头
        String fDSupplyID = AddBack_HeadBean.getFSupplyID();
        String fpUser = AddBack_HeadBean.getFPUser();
        String fUser = AddBack_HeadBean.getFUser();
        String fyUser = AddBack_HeadBean.getFYUser();
        String fbUser = AddBack_HeadBean.getFBUser();
        String fdcStock = AddBack_HeadBean.getFDCStockID();

        if (mUser != null) {
            String id = mUser.getId();
            AddBack_HeadBean.setFUser(id);
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "当前用户获取失败，请重新登陆！", Snackbar.LENGTH_SHORT).show();
        }

        if (!StringUtils.isEmpty(fDSupplyID) && !StringUtils.isEmpty(fdcStock)
                && !StringUtils.isEmpty(fbUser) && !StringUtils.isEmpty(fyUser)) {


            AddBack_HeadBean.setFSupplyID(fDSupplyID);
            AddBack_HeadBean.setFPUser(fpUser);
            AddBack_HeadBean.setFYUser(fyUser);
            AddBack_HeadBean.setFBUser(fbUser);
            AddBack_HeadBean.setFDCStockID(fdcStock);
            AddBack_HeadBean.setFtype("-1");//1代表出库，-1是退货


            //表体
            List<AddSaleInt_bodyBean> bodys = new ArrayList<>();
            List<AddSaleInt_body_InOutList_Bean> bodyInOuts = new ArrayList<>();

            //判断列表进来
            if (environmentList != null && environmentList.size() > 0) {
                for (int i = 0; i < environmentList.size(); i++) {
                    AddSaleInt_body_InOutList_Bean bodyInOutsBean = new AddSaleInt_body_InOutList_Bean();
                    if (i == 0) {
                        bodyInOutsBean.setFCusId(fDSupplyID);
                    } else {
                    }
                    bodyInOutsBean.setFText(environmentList.get(i));
                    bodyInOuts.add(bodyInOutsBean);
                }
            }

//            for (int i = 0; i < mFbillNumberList.size(); i++) {
//                AddSaleInt_body_InOutList_Bean bodyInOutsBean = new AddSaleInt_body_InOutList_Bean();
//                if (i == 0) {
//                    bodyInOutsBean.setFCusId(fDSupplyID);
//                } else {
//                }
//                bodyInOutsBean.setFText(mFbillNumberList.get(i));
//
//                bodyInOuts.add(bodyInOutsBean);
//            }
            for (int i = 0; i < addSyncBeen_List.size(); i++) {
                AddSaleInt_bodyBean bodyBean = new AddSaleInt_bodyBean();
                Add_bodyBack_Bean addSyncBeans = addSyncBeen_List.get(i);

                String fCount = addSyncBeans.getCount();
                if (fCount.contains(".")) {
                    String counts = fCount.substring(0, fCount.indexOf("."));
                    bodyBean.setFQty(counts);
                } else {
                    bodyBean.setFQty(fCount);
                }
                String unit_id = addSyncBeans.getUnit_id();
                String fdcStockID = addSyncBeans.getTDCStockID();  //表体id
                String id = addSyncBeans.getId();

                if (!StringUtils.isEmpty(fdcStockID)) {
                    bodyBean.setFStockId(fdcStockID);
                } else if (!StringUtils.isEmpty(fdcStock)) {
                    bodyBean.setFStockId(fdcStock);
                } else {
                    bodyBean.setFStockId("0");
                }

                bodyBean.setFUnitId(unit_id);
                bodyBean.setFProductID(id);

                bodys.add(bodyBean);
            }

            showWaitDialog();
            AddBack_HB_Bean addSaleIntHbBean = new AddBack_HB_Bean();
            addSaleIntHbBean.setBodyList(bodys);
            addSaleIntHbBean.setInoutList(bodyInOuts);
            addSaleIntHbBean.setHeadDetail(AddBack_HeadBean);

            Gson gson = new Gson();
            String json = gson.toJson(addSaleIntHbBean);
            String token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
            CM cm = new CM();
            cm.setToken(token);
            cm.setData(json);
            RetrofitSingleton.getApiService(mActivity).
                    StockBillSubmit(cm)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "必填信息不能为空！", Snackbar.LENGTH_SHORT).show();
        }
    }

    //保存
    private void saveMat() {
        ArrayList<Add_bodyBack_Bean> addSyncBeen_List = mAdapter.getBackList();
        if (addSyncBeen_List != null && addSyncBeen_List.size() > 0) {

            AddBack_HeadBean.setUsername(AppContext.getInstance().getCurrentUser().getName());
            AddSale_Manager.getInstance(mActivity).inOrSale_back(AddBack_HeadBean);
            AddBack_HeadBean lastHead_saleout = AddSale_Manager.getInstance(mActivity).getLastHead_saleback();

            for (int i = 0; i < addSyncBeen_List.size(); i++) {
                addSyncBeen_List.get(i).setHeadBack(lastHead_saleout);
            }

            AddSale_Manager.getInstance(mActivity).insertBackMatsback(addSyncBeen_List);


            Snackbar.make(mActivity.getWindow().getDecorView(), "保存成功!", Snackbar.LENGTH_SHORT).show();

            Intent intent = new Intent(AppConfig.SALE_Back_SAVE);
            mActivity.sendBroadcast(intent);

            isSave = true;
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mActivity.finish();
                    Bundle bundle = new Bundle();
                    UIHelper.showSimpleBack(mActivity, SimpleBackPage.ADD_BACK_MAT, bundle, "退货");
                }
            }, 500);//3秒后执行Runnable中的run方法

        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "未扫描单据不能保存!", Snackbar.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            mActivity.unregisterReceiver(mSamDataReceiver);
        } catch (Exception ex) {
        }
        ButterKnife.reset(this);
    }

    @Override
    public void onFHCKClick(Add_bodyBack_Bean bean, int position) {
        this.position = position;
        Bundle bundle = new Bundle();
        bundle.putString("type", "shck");
        UIHelper.showSimpleBackForResult(this, mActivity, 7, SimpleBackPage.CUST_PHEON, bundle, "收货仓库");
    }

    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(getActivity().getWindow().getDecorView(), errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            if (result.isSuccess()) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "提交成功!", Snackbar.LENGTH_SHORT).show();
                if ("show".equals(mType) || isSave) {
                    AddSale_Manager.getInstance(mActivity).delAllByIdBack(AddBack_HeadBean.getId());
                    AddSale_Manager.getInstance(mActivity).delAllByHeadIdBack(AddBack_HeadBean.getId());//提交成功后删除缓存
                }
                mActivity.finish();
            } else {
                Snackbar.make(mActivity.getWindow().getDecorView(), result.getMessage(), Snackbar.LENGTH_SHORT).show();
            }
        }
    };

}

